using System;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;

namespace EntityKit.Runtime
{
    /// <summary>
    /// 实体管理器核心类，负责实体的添加、移除和生命周期管理
    /// </summary>
    public static partial class EntityManager
    {
        /// <summary>
        /// 实体是否初始化
        /// </summary>
        public static bool IsInitialized { get; private set; }

        // 存储类型到实体列表的映射
        private static Dictionary<Type, List<IEntity>> mTypeToEntities = new Dictionary<Type, List<IEntity>>();

        // ID到实体的映射，用于精确查找
        private static Dictionary<string, IEntity> mIdToEntity = new Dictionary<string, IEntity>();

        /// <summary>
        /// 初始化，应该加载所有在场景中预制的实体列表
        /// </summary>
        public static void Initialized(List<IEntity> entities)
        {
            if (IsInitialized)
                throw new Exception("实体系统已经初始化.");
            IsInitialized = true;
            if (entities.Count == 0)
                return;
            mTypeToEntities = new Dictionary<Type, List<IEntity>>();
            mIdToEntity = new Dictionary<string, IEntity>();
            foreach (var entity in entities)
                AddEntity(entity, false);
            foreach (var entity in entities)
            {
                if (entity.IsInit)
                    throw new Exception($"实体 {entity.EntityID} 已经初始化过.");
                entity.OnInit();
            }

        }

        /// <summary>
        /// 更新所有实体
        /// </summary>
        public static void Update()
        {
            if (!IsInitialized)
                return;
            // 创建一个副本列表以避免在迭代时修改集合
            var entitiesToUpdate = mIdToEntity.Values.Where(entity => entity.IsInit).ToList();
            foreach (var entity in entitiesToUpdate)
            {
                entity.OnUpdate();
            }
        }

        /// <summary>
        /// 释放所有实体
        /// </summary>
        public static void Release()
        {
            if (!IsInitialized)
                throw new Exception("请先初始化实体系统");
            IsInitialized = false;

            try
            {
                // 创建一个副本列表以避免在迭代时修改集合
                var entitiesToRelease = mIdToEntity.Values.ToList();
                if (!entitiesToRelease.All(CanReleaseEntity))
                    throw new Exception("释放所有实体失败，请检查实体状态");
                foreach (var entity in entitiesToRelease)
                {
                    if (!entity.IsInit)
                        throw new Exception($"不能释放未初始化的实体{entity.EntityID}");
                    entity.OnRelease();
                }
            }
            finally
            {
                mTypeToEntities.Clear();
                mIdToEntity.Clear();
            }
        }
    }
}